<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span v-show="id">编辑企业</span>
        <span v-show="!id">添加企业</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" label-width="100px" :rules="ruleForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in IndustryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- 1.action="#", 不适应action方式上传-->
              <!-- 2.:http-request使用自定义上传 -->
              <!-- 3.list-type="picture-card"可以查看图片 -->
              <el-upload
                class="upload-demo"
                action="#"
                list-type="picture-card"
                :http-request="uploadChange"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <!-- 回显图片 -->
              <img v-show="id" :src="addForm.businessLicenseUrl" alt="" width="100">
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="reset">重置</el-button>
        <el-button v-show="!id" type="primary" @click="submit">确定</el-button>
        <el-button v-show="id" type="primary" @click="submit">编辑</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { Industry, update, addSubmit, editList, editSubmit } from '@/api/add'
export default {
  data() {
    return {
      fileList: [],
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      ruleForm: {
        name: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '企业法人不能为空', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址不能为空', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业不能为空', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人不能为空', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系方式不能为空', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '电话号码格式错误', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '文件不能为空', trigger: 'blur' }
        ]
      },
      IndustryList: []
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    this.getList()
    if (this.id) {
      this.editListCreate()
    }
  },
  methods: {
    async editListCreate() {
      const { data: {
        name,
        legalPerson,
        registeredAddress,
        industryCode,
        contact,
        contactNumber,
        businessLicenseUrl,
        businessLicenseId
      }} = await editList(this.id)
      this.addForm = { name,
        legalPerson,
        registeredAddress,
        industryCode,
        contact,
        contactNumber,
        businessLicenseUrl,
        businessLicenseId }
      // const res = await editList(this.id)
      // this.addForm = res.data
    },
    // 点击重置
    reset() {
      this.$refs.ruleForm.resetFields()
      this.addForm.businessLicenseUrl = ''
      this.addForm.businessLicenseId = ''
    },
    // 编写校验逻辑
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传营业执照图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传营业执照图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    async submit() {
      try {
        await this.$refs.ruleForm.validate()
        if (this.id) {
          await editSubmit({ ...this.addForm, id: this.id })
          this.$message.success('编辑成功')
        } else {
          await addSubmit(this.addForm)
          this.$message.success('添加成功')
        }
        this.$router.back()
      } catch (error) {
        console.log('表单校验失败')
      }
    },
    // async submit() {
    //   this.$refs.ruleForm.validate(async(valid) => {
    //     if (!valid) return
    //     await this.$refs.ruleForm.validate()
    //     await addSubmit(this.addForm)
    //     this.$router.back()
    //     this.$message.success('添加成功')
    //   })
    // },
    async getList() {
      const res = await Industry()
      // console.log(this.IndustryList)
      this.IndustryList.push(...res.data)
    },
    // 上传图片
    async uploadChange(data) {
      // console.log(data.file)
      // 实例化对象
      const fm = new FormData()
      fm.append('file', data.file)
      fm.append('type', 'businessLicense')
      // console.log(fm)
      const res = await update(fm)
      this.$message.success('上传成功')
      // console.log(res, '结果')
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      this.$refs.ruleForm.validateField('businessLicenseId')// validateField清除校验字段
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
